#include "Saver.h"

int Saver::save(QString file_name,GameDesk * game_desk, QVector<Player *> players, int vis_template)
{
   QDomDocument doc("save_game");
   QFile file(file_name);
   if (!file.open(QIODevice::WriteOnly))
       return FILE_ERROR;

   QDomElement xml = doc.createElement("xml");
   doc.appendChild(xml);

   QDomElement board = doc.createElement("board");
   board.setAttribute("size",game_desk->Size());
   board.setAttribute("template", vis_template);
   //board.setAttribute("players_number", );

   QDomElement elem;
   GameSquare * game_square;

   int size = game_desk->Size();

   for (int i = 0; i < (3 * size - 3) * 4 ; i++)
   {
     //elem = new QDomElement();
     elem = doc.createElement("square");

     elem.setAttribute("index", i);
     game_square = game_desk->getSquare(i, SQUARE_SHARED, 0);
     elem.setAttribute("icon", game_square->getIconNumber());
     board.appendChild(elem);
   }

   QDomElement e_home;
   QDomElement home_square;

   const int MAX_HOMES = 4;
   for (int i = 0; i < players.size(); i++) {
      e_home = doc.createElement("end_home");
      e_home.setAttribute("player", players[i]->seqNumber());
      board.appendChild(e_home);

     for (int y = 0; y < MAX_HOMES; y++) {
        home_square = doc.createElement("square");
        game_square = game_desk->getSquare(y, SQUARE_END_HOME, players[i]->seqNumber());
        home_square.setAttribute("icon", game_square->getIconNumber());
        e_home.appendChild(home_square);
     }

   }

   xml.appendChild(board);

   QDomElement player;
   QDomElement piece;

   for (int i = 0; i < players.size(); i++) {
      player = doc.createElement("player");

      player.setAttribute("nickname", players[i]->getNickname());
      player.setAttribute("seq_number", players[i]->seqNumber());
      player.setAttribute("type", players[i]->getPlayerType());

      const int MAX_PIECES = 4;

      for (int y = 0; y < MAX_PIECES; y++) {
         piece = doc.createElement("piece");
         piece.setAttribute("index", players[i]->getPieceIndex(y));
         player.appendChild(piece);
      }

      xml.appendChild(player);
   }

   QTextStream ts( &file );
   ts << doc.toString();

   file.close();

   return OK;
}
